﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using System.Web;
using System.Security.Cryptography;
using System.Net;

namespace WebAPILib
{
    public class BaseInfo
    {

        public List<string> Keywords { get; set; }

        public List<string> PreFixes { get; set; }

        public List<string> SurFixes { get; set; }

        public List<string> SpellCodes { get; set; }

        public static List<string> GetParamsFromFile(string path)
        {
            List<string> Lines = new List<string>();
            string strLine;
            try
            {
                FileStream aFile = new FileStream(path, FileMode.Open);
                StreamReader sr = new StreamReader(aFile);
                strLine = sr.ReadLine();
                Lines.Add(strLine);
                //Read data in line by line 
                while (strLine != null)
                {
                    strLine = sr.ReadLine();

                    Lines.Add(strLine);
                }

                sr.Close();

                return Lines;
            }
            catch (IOException ex)
            {
                return new List<string>();
            }
        }

        public static List<string> GetParamsFromFiles(string[] pathes)
        {
            List<string> Lines = new List<string>();

            foreach (string path in pathes)
            {
                Lines.AddRange(GetParamsFromFile(path));
            }

            return Lines;
        }


        public BaseInfo()
        {
            Keywords = GetParamsFromFile(@"E:\域名查询参数文件夹\关键字.txt");

            PreFixes = GetParamsFromFile(@"E:\域名查询参数文件夹\前缀.txt");

            SurFixes = GetParamsFromFile(@"E:\域名查询参数文件夹\后缀.txt");

            SpellCodes = GetParamsFromFile(@"E:\域名查询参数文件夹\双拼码.txt");

            //SpellCodes=GetParamsFromXMLFile(@"E:\域名查询参数文件夹\双拼码库.xml");

        }

        private List<string> GetParamsFromXMLFile(string path)
        {
            DataSet ds = new DataSet();

            ds.ReadXml(path);

            DataTable dt = ds.Tables[0];
            List<string> list = new List<string>();
            foreach (DataRow dr in dt.Rows)
            {
                list.Add(dr[0].ToString());
            }

            return list;
        }



        /// <summary>
        /// 访问URL地址
        /// </summary>
        /// <param name="url">URL地址</param>
        /// <param name="postDataStr">参数</param>
        /// <param name="Encod">编码方式</param>
        /// <returns></returns>
        public static string CallWebPage(string url, string postDataStr, Encoding Encod)
        {
            string rStr = "";
            System.Net.WebRequest req = null;
            System.Net.WebResponse resp = null;
            System.IO.Stream os = null;
            System.IO.StreamReader sr = null;
            try
            {
                //创建连接
                req = System.Net.WebRequest.Create(url);
                //设置访问方式和发送的请求数据的内容类型
                if (string.IsNullOrEmpty(postDataStr))
                {
                    req.ContentType = "application/x-www-form-urlencoded";
                    req.Method = "GET";
                }
                else
                {
                    req.ContentType = "application/x-www-form-urlencoded";
                    req.Method = "POST";
                    if (Encod == null)
                    {
                        Encod = System.Text.Encoding.Default;
                    }
                    byte[] bytes = Encod.GetBytes(postDataStr);
                    req.ContentLength = bytes.Length;
                    os = req.GetRequestStream();
                    os.Write(bytes, 0, bytes.Length);
                    os.Close();
                }
                //读取返回结果
                resp = req.GetResponse();
                sr = new System.IO.StreamReader(resp.GetResponseStream(), System.Text.Encoding.Default);
                rStr = sr.ReadToEnd();
            }
            catch (Exception ex1)
            {
                //LogUtil.Warn("HttpUtil.CallWebPage 异常：" + ex1.Message);
            }
            finally
            {
                try
                {
                    //关闭资源
                    if (os != null)
                    {
                        os.Dispose();
                        os.Close();
                    }
                    if (sr != null)
                    {
                        sr.Dispose();
                        sr.Close();
                    }
                    if (resp != null)
                    {
                        resp.Close();
                    }

                    if (req != null) req = null;
                }
                catch (Exception ex2)
                {
                    //LogUtil.Exception("HttpUtil.CallWebPage 关闭连接异常：" + ex2.Message);
                }
            }
            return rStr;
        }

        public static void SaveCache()
        {
            //DomainInfoCache.Save();
           // DomainInfoCacheTxt.Save();

           
        }


        /// <summary>
        /// URL请求参数UTF8编码
        /// </summary>
        /// <param name="value">源字符串</param>
        /// <returns>编码后的字符串</returns> 
        public static string Utf8Encode(string value)
        {
            return HttpUtility.UrlEncode(value, System.Text.Encoding.UTF8);
        }

        /// <summary>
        /// SHA1加密字符串
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <returns>加密后的字符串</returns> 
        public static string SHA1(string source)
        {
            byte[] value = Encoding.UTF8.GetBytes(source);
            SHA1 sha = new SHA1CryptoServiceProvider();
            byte[] result = sha.ComputeHash(value);

            string delimitedHexHash = BitConverter.ToString(result);
            string hexHash = delimitedHexHash.Replace("-", "");

            return hexHash;
        }


        /// <summary>
        /// URL请求
        /// </summary>
        /// <param name="url">URL地址</param>
        /// <param name="status">URL请求响应状态码</param>
        /// <returns>请求结果</returns> 
        public static string RequestUrl(string url, out int status)
        {
            string result = null;
            status = 0;
            HttpWebResponse response = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
                response = (HttpWebResponse)request.GetResponse();
                Encoding responseEncoding = Encoding.GetEncoding(response.CharacterSet);
                using (StreamReader sr = new StreamReader(response.GetResponseStream(), responseEncoding))
                {
                    result = sr.ReadToEnd();
                }
                status = (int)response.StatusCode;
            }
            catch (WebException wexc1)
            {
                // any statusCode other than 200 gets caught here
                if (wexc1.Status == WebExceptionStatus.ProtocolError)
                {
                    // can also get the decription: 
                    //  ((HttpWebResponse)wexc1.Response).StatusDescription;
                    status = (int)((HttpWebResponse)wexc1.Response).StatusCode;
                }
            }
            finally
            {
                if (response != null)
                    response.Close();
            }
            return result;
        }


    }
}
